package com.tang.state;

import com.tang.bean.WaterSensor;
import com.tang.functions.WaterSensorMapFunction;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.scala.typeutils.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Optional;

/**
 * 状态后端的代码配置
 *
 * @author tang
 * @since 2023/7/12 11:20
 */
public class StateBackendDemo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        env.setParallelism(1);

        // 1.使用hashMap状态后端
        HashMapStateBackend hashMapStateBackend = new HashMapStateBackend();
        env.setStateBackend(hashMapStateBackend);
        // 2.使用rocksdb状态后端
        EmbeddedRocksDBStateBackend stateBackend = new EmbeddedRocksDBStateBackend();
        env.setStateBackend(stateBackend);

        env.socketTextStream("192.168.70.141", 7777)
                .map(new WaterSensorMapFunction())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((element, recordTimestamp) -> element.getTs() * 1000L)
                ).keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, WaterSensor>() {

                    private ValueState<Integer> lastVcState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        super.open(parameters);
                        lastVcState = getRuntimeContext().getState(new ValueStateDescriptor<>("lastVcState", Types.INT()));
                    }

                    @Override
                    public void processElement(WaterSensor waterSensor,
                                               KeyedProcessFunction<String, WaterSensor, WaterSensor>.Context ctx,
                                               Collector<WaterSensor> out) throws Exception {
                        // 3. 进行判断
                        Integer lastVc = Optional.ofNullable(lastVcState.value()).orElse(0);
                        Integer vc = waterSensor.getVc();
                        // Math.abs是啥? 取绝对值
                        if (Math.abs(vc - lastVc) > 10) {
                            System.out.println("传感器=" + waterSensor.getId() + "==>当前水位值=" + vc + ",与上一条水位值=" + lastVc + ",相差超过10！！！！");
                            out.collect(waterSensor);
                            lastVcState.update(vc);
                        } else {
                            System.out.println("传感器=" + waterSensor.getId() + "==>当前水位值=" + vc + ",上一条水位值=" + lastVc);
                        }
                    }

                }).print();

        env.execute();
    }

}
